package com.mentalhealthplatform.teacherV2.service;

import com.mentalhealthplatform.appModels.Assessment;
import com.mentalhealthplatform.teacherV2.repository.AssessmentRepositoryV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 负责处理与评估相关的业务逻辑。
 */
@Service
public class AssessmentServiceV2 {
    @Autowired
    private AssessmentRepositoryV2 assessmentRepositoryV2;

    /**
     * 获取所有评估的列表。
     *
     * @return 所有评估的列表
     */
    public List<Assessment> getAllAssessments() {
        return assessmentRepositoryV2.findAllWithStudent();
    }

    /**
     * 根据ID获取特定评估。
     *
     * @param id 评估的ID
     * @return 评估的可选值
     */
    public Optional<Assessment> getAssessmentById(Long id) {
        return assessmentRepositoryV2.findByIdWithStudent(id);
    }

    /**
     * 根据关键词搜索评估。
     *
     * @param keyword 搜索关键词
     * @return 满足条件的评估列表
     */
    public List<Assessment> searchAssessments(String keyword) {
        List<Assessment> assessments = assessmentRepositoryV2.findByStudent_Number(keyword);
        if (assessments.isEmpty()) {
            assessments = assessmentRepositoryV2.findByEvaluationContaining(keyword);
        }
        return assessments;
    }

    /**
     * 获取所有评估及其相关学生信息。
     *
     * @return 包含学生的所有评估列表
     */
    public List<Assessment> findAllWithStudent() {
        return assessmentRepositoryV2.findAllWithStudent();
    }

    // 新增方法：获取统计数据
    public Map<String, Object> getStatistics() {
        List<Assessment> assessments = assessmentRepositoryV2.findAll();

        // 计算不同等级所占比例
        Map<String, Long> levelDistribution = assessments.stream()
                .collect(Collectors.groupingBy(Assessment::getEvaluation, Collectors.counting()));

        // 计算测评数据和操作时间统计
        List<Map<String, Object>> operationTimes = assessments.stream()
                .map(a -> {
                    Map<String, Object> map = new HashMap<>();
                    if (a.getSubmittedTime() != null) {
                        map.put("date", a.getSubmittedTime().toLocalDate().toString()); // 提交日期
                        map.put("time", a.getSubmittedTime().toString()); // 提交时间
                    } else {
                        map.put("date", "N/A");
                        map.put("time", "N/A");
                    }
                    map.put("score", a.getScore()); // 测评成绩
                    return map;
                })
                .toList();

        return Map.of(
                "levelDistribution", levelDistribution,
                "operationTimes", operationTimes
        );
    }

    public List<Assessment> findByStudentId(UUID studentId) {
        return assessmentRepositoryV2.findByStudentId(studentId);
    }
}